/*
 * @Author: 彭林
 * @Date: 2021-06-11 13:54:54
 * @LastEditTime: 2021-07-14 18:20:40
 * @LastEditors: 彭林
 * @Description:
 * @FilePath: /saas-app/app/service/poetry.go
 */
/*
 * @Author: 彭林
 * @Date: 2021-05-14 15:15:56
 * @LastEditTime: 2021-05-14 15:17:33
 * @LastEditors: 彭林
 * @Description:
 * @FilePath: /saas-app/app/service/districts.go
 */
package service

import (
	"saas-app/app/dao"
	"saas-app/app/define"
	"saas-app/app/model"
)

type PeotryRepository interface {
	CreatePeotry(peotry *model.Peotry, note_list []*define.NoteLists) uint
	CreateNewPeotry(peotry *model.Peotry)
	CreateNoteList(note_list []*define.NoteLists)
	GetPeotryLastId() int
	GetPeotryList(page, limit int) (result interface{}, total int)
	GetInfo(peotry_id uint) *model.Peotry
}

type peotry struct{}

func PeotryService() PeotryRepository {
	return &peotry{}
}

func (p peotry) CreatePeotry(peotry *model.Peotry, note_list []*define.NoteLists) uint {

	record, _ := dao.Peotry.Where("peotry_id = ?", peotry.PeotryId).FindOne()
	oldpeotry := model.Peotry{}
	record.Struct(&oldpeotry)
	if oldpeotry.Id != 0 {
		return 0
	}

	PeotryService().CreateNewPeotry(peotry)
	PeotryService().CreateNoteList(note_list)
	return peotry.PeotryId
}

func (p peotry) CreateNewPeotry(peotry *model.Peotry) {
	dao.Peotry.Save(peotry)
}

func (p peotry) CreateNoteList(note_list []*define.NoteLists) {
	for _, v := range note_list {
		dao.NoteList.Save(v)
	}
}

func (p peotry) GetPeotryLastId() int {

	peotrys := ([]*model.Peotry)(nil)

	err := dao.Peotry.Order("peotry_id desc").Limit(1).Structs(peotrys)

	if err != nil {
		return 0
	}

	if len(peotrys) == 0 {
		return 0
	}
	return int(peotrys[0].PeotryId)
}

func (p peotry) GetPeotryList(page, limit int) (result interface{}, total int) {

	if page <= 0 || limit <= 0 {
		panic("参数错误")
	}

	db := dao.Peotry.Order("peotry_id desc")
	total, _ = db.FindCount()

	result, err := db.Offset((page - 1) * limit).Limit(limit).FindAll()

	if err != nil {
		panic(err)
	}

	return result, total
}

func (p peotry) GetInfo(peotry_id uint) *model.Peotry {

	if peotry_id <= 0 {
		panic("参数错误")
	}

	peotry := model.Peotry{}

	err := dao.Peotry.Where("peotry_id = ?", peotry_id).Struct(&peotry)

	if err != nil {
		panic(err)
	}

	return &peotry
}
